<?php

namespace App\Http\Controllers\Activity;

use App\Http\Controllers\Controller;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ActivityCancelController extends Controller
{
    /**
     * 取消霸王餐
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {

        $all = $this->all;
        $act_id = $all['act_id'];

        try {
            DB::beginTransaction();

            // 查询活动
            $activity = DB::table('lottery_activity')->where('act_id', '=', $act_id)->lockForUpdate()->first();
            $activity = json_decode(json_encode($activity), true);

            // 霸王餐状态为已完成或已取消时，不允许再执行取消操作
            if ($activity['status'] === Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_SUCCESS || $activity['status'] === Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_CANCEL) {
                DB::rollBack();
                return $this->setReturnJson(-1, '当前霸王餐状态为' . Data::$lotteryActivityStatus[$activity['status']] . '，不允许取消');
            }

            // 查询余额,保证探店余额充足
            $remaining = DB::table('lottery_remaining')->where('we_id', '=', $activity['creator'])->lockForUpdate()->first();
            $remaining = json_decode(json_encode($remaining), true);
            if (!$remaining['in_use_times']) {
                DB::rollBack();
                Log::emergency('取消霸王餐活动失败，探店余额不足', ['activity' => $activity, 'remaining' => $remaining]);
                return $this->setReturnJson(-1, '取消失败');
            }


            // 更新霸王餐活动信息
            DB::table('lottery_activity')->where('act_id', '=', $act_id)->update([
                'status' => Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_CANCEL, // 修改为取消状态
                'is_stop' => 1,
                'cancel_user' => $this->userInfo['id'],
                'canceled_at' => date('Y-m-d H:i:s'),
                'remark'=>'管理员取消',
            ]);

            // 退回商家余额
            DB::table('lottery_remaining')->where('lr_id', '=', $remaining['lr_id'])->increment('remaining_times');
            DB::table('lottery_remaining')->where('lr_id', '=', $remaining['lr_id'])->decrement('in_use_times');
            // 记录操作日志
            DB::table('lottery_remaining_log')->insert([
                'lr_id' => $remaining['lr_id'],
                'action' => 3,//退回
                'action_num' => 1,
                'rest_num' => $remaining['remaining_times'] + 1,
                'in_use_num' => $remaining['in_use_times'] - 1,
            ]);

            // 删除中奖信息
            DB::table('lottery_draw_detail')->where('act_id', '=', $act_id)->update(['is_delete' => 1]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(ActivityCancelController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '取消失败');
        }
        return $this->setReturnJson(0, '取消成功');

    }

}
